//
//  ViewController.m
//  MathMastersAsteroids
//
//  Created by Jordon Phillips on 3/12/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "ViewController.h"


@implementation ViewController
@synthesize glView, lastView, label,options, tutorial, ranking, difficultySwitch, difficultyDesc, tutorialImage, tutorialDesc, tutNext, tutPrev, rankingSwitch, rankings;

//draws the game
- (IBAction)drawEAGLView:(id)sender {
	if(resume){//if a game is currently being played
		label.textColor = [UIColor whiteColor];
		if(glView.difficulty==0)
			label.text=[NSString stringWithFormat:@"Last Score(Easy): %i",glView.score];
		else if(glView.difficulty==1)
			label.text=[NSString stringWithFormat:@"Last Score(Medium): %i",glView.score];
		else if(glView.difficulty==2)
			label.text=[NSString stringWithFormat:@"Last Score(Hard): %i",glView.score];
		[self addRanking:glView.score :glView.difficulty];
		self.view=lastView;
	}
	[UIApplication sharedApplication].statusBarHidden = YES;
	self.view.bounds = CGRectMake(0,0,320,500);
    CGRect rect = [[UIScreen mainScreen] applicationFrame];
    glView = [[EAGLView alloc] initWithFrame:CGRectMake(0, 0, rect.size.width, rect.size.height)];
    lastView=self.view;
	[self.view addSubview:glView];
	[self.view bringSubviewToFront:glView];
	gameCheck = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(checkGame) userInfo:nil repeats:YES];
    resumeButton.hidden=TRUE;
	if(sound)
		[glView soundOn];
	else
		[glView soundOff];
	if(music)
		glView.musicToggle=TRUE;
	else
		glView.musicToggle=FALSE;
	[glView setDifficulty:difficulty];
	[glView startAnimation];
}
//resumes game
- (IBAction)resumeGame:(id)sender{
	if(resume){
		[UIApplication sharedApplication].statusBarHidden = YES;
		self.view.bounds = CGRectMake(0,0,320,500);
		glView.hidden = FALSE;
		resume = FALSE;
		resumeButton.hidden=TRUE;
		if(sound)
			[glView soundOn];
		else
			[glView soundOff];
		if(music)
			glView.musicToggle=TRUE;
		else
			glView.musicToggle=FALSE;
		[glView startAnimation];
	}
}

//checks if game is over or paused
-(void)checkGame{
	if(glView.pause){
		label.text=[NSString stringWithFormat:@"Resume Game"];
		[UIApplication sharedApplication].statusBarHidden = NO;
		self.view.bounds = CGRectMake(0,0,320,460);
		[glView stopAnimation];
		glView.hidden = TRUE;
		resume = TRUE;
		glView.pause = FALSE;
		resumeButton.hidden=FALSE;
		glView.resetTouchPoint;
		glView.pause = FALSE;
	}
	if(glView.animating){
		if(glView.player.sprite.dead){
			label.textColor = [UIColor whiteColor];
			if(glView.difficulty==0)
				label.text=[NSString stringWithFormat:@"Last Score(Easy): %i",glView.score];
			else if(glView.difficulty==1)
				label.text=[NSString stringWithFormat:@"Last Score(Medium): %i",glView.score];
			else if(glView.difficulty==2)
				label.text=[NSString stringWithFormat:@"Last Score(Hard): %i",glView.score];
			[UIApplication sharedApplication].statusBarHidden = NO;
			self.view.bounds = CGRectMake(0,0,320,460);
			[glView stopAnimation];
			glView.hidden = TRUE;
			[self addRanking:glView.score :glView.difficulty];
			self.view=lastView;
		}
	}

	
}
//opens the options menu
- (IBAction)openOptions:(id)sender{
	[self.view addSubview:options];
	[self.view bringSubviewToFront:options];
	options.hidden=FALSE;
}
//closes the options menu
- (IBAction)closeOptions:(id)sender{
	options.hidden=TRUE;
	[options removeFromSuperview];
}
//toggles sound on and off
- (IBAction)soundToggle:(id)sender{
	if(sound)
		sound=FALSE;
	else
		sound=TRUE;
}
//toggles music on and off
- (IBAction)musicToggle:(id)sender{
	if(music)
		music=FALSE;
	else
		music=TRUE;
}
//changes the difficulty of a new game
- (IBAction)changeDifficulty:(id)sender{
	difficulty=difficultySwitch.selectedSegmentIndex;
	if(difficulty==0)
		difficultyDesc.text=@"On the easy difficulty there is only addition and subtraction of numbers 0 to 5.  Subtraction never results in a negative number.";
	else if(difficulty==1)
		difficultyDesc.text=@"On the medium difficulty there is addition, subtraction and multiplication of numbers 0 to 5.  Subtraction can result in a negative number.";
	else if(difficulty==2)
		difficultyDesc.text=@"On the hard difficulty there is addition, subtraction and multiplication of numbers 0 to 9.  Subtraction can result in a negative number.";
}
//goes to the next page in the tutorial
- (IBAction)tutorialNext:(id)sender{
	if(tutPage==0){
		tutPage++;
		tutorialImage.image=shoot1;
		tutorialDesc.text=@"SHOOTING\n When you are not touching the screen your ship will continuously shoot.  Touch the screen to stop shooting. Shoot asteroids to destroy them to gain points and reveal the number inside. Numbers can be destroyed as well.\n 2/5 ";
		tutPrev.hidden=FALSE;
	}else if(tutPage==1){
		tutPage++;
		tutorialImage.image=equation1;
		tutorialDesc.text=@"SOLVING EQUATIONS\n If you move onto a number not within an asteroid you will collect it.  If the number completes the equation you get points and a new equation appears. Asteroids only come if there is no asteroid or number in its row. \n 3/5 ";
	}else if(tutPage==2){
		tutPage++;
		tutorialImage.image=wrong1;
		tutorialDesc.text=@"COLLECTING A WRONG NUMBER\n If you collect the wrong number you will lose time and health.  When the time bar completely empties the equation is changed.  When the time bar is low there is a higher chance of the needed number appearing.  \n 4/5 ";
	}else if(tutPage==3){
		tutPage++;
		tutorialImage.image=pause;
		tutNext.hidden=TRUE;
		tutorialDesc.text=@"PAUSING AND GAME OVER\n Touch the pause symbol to pause the game and return to the main menu.  The game ends if you either start a new game or if you run out of health.  \n \n \n 5/5 ";
	}
}
//goes to the previous page in the tutorial
- (IBAction)tutorialPrev:(id)sender{
	if(tutPage==1){
		tutPage--;
		tutorialImage.image=move1;
		tutorialDesc.text=@"MOVING\n Touch the screen and your ship will move towards just in front of the point that you touch. The ship will stop moving if you stop touching the screen. You will lose health if you crash into an asteroid.  \n \n 1/5 ";
		tutPrev.hidden=TRUE;
	}else if(tutPage==2){
		tutPage--;
		tutorialImage.image=shoot1;
		tutorialDesc.text=@"SHOOTING\n When you are not touching the screen your ship will continuously shoot.  Touch the screen to stop shooting. Shoot asteroids to destroy them to gain points and reveal the number inside. Numbers can be destroyed as well.\n 2/5 ";
	}else if(tutPage==3){
		tutPage--;
		tutorialImage.image=equation1;
		tutorialDesc.text=@"SOLVING EQUATIONS\n If you move onto a number not within an asteroid you will collect it.  If the number completes the equation you get points and a new equation appears. Asteroids only come if there is no asteroid or number in its row. \n 3/5 ";
	}else if(tutPage==4){
		tutPage--;
		tutorialImage.image=wrong1;
		tutNext.hidden=FALSE;
		tutorialDesc.text=@"COLLECTING A WRONG NUMBER\n If you collect the wrong number you will lose time and health.  When the time bar completely empties the equation is changed.  When the time bar is low there is a higher chance of the needed number appearing.  \n 4/5 ";
	}
	
}
//opens the tutorial
- (IBAction)openTutorial:(id)sender{
	[self.view addSubview:tutorial];
	[self.view bringSubviewToFront:tutorial];
	tutorial.hidden=FALSE;
}
//closes the tutorial
- (IBAction)closeTutorial:(id)sender{
	tutorial.hidden=TRUE;
	[tutorial removeFromSuperview];
}
//updates the tutorial image
- (void)updateImage{
	if(tutImage){
		tutImage=FALSE;
		if(tutPage==0){
			tutorialImage.image=move1;
		}else if(tutPage==1){
			tutorialImage.image=shoot1;
		}else if(tutPage==2){
			tutorialImage.image=equation1;
		}else if(tutPage==3){
			tutorialImage.image=wrong1;
		}
		
	}else{
		tutImage=TRUE;
		if(tutPage==0){
			tutorialImage.image=move2;
		}else if(tutPage==1){
			tutorialImage.image=shoot2;
		}else if(tutPage==2){
			tutorialImage.image=equation2;
		}else if(tutPage==3){
			tutorialImage.image=wrong2;
		}
	}
}
//opens the ranking menu
- (IBAction)openRanking:(id)sender{
	[self.view addSubview:ranking];
	[self.view bringSubviewToFront:ranking];
	ranking.hidden=FALSE;
}
//closes the ranking menu
- (IBAction)closeRanking:(id)sender{
	ranking.hidden=TRUE;
	[ranking removeFromSuperview];
}
//changes the rankings menu based on difficulty
- (IBAction)changeRanking:(id)sender{
	rankingDifficulty=rankingSwitch.selectedSegmentIndex;
	if(rankingDifficulty==0)
		rankings.text=[NSString stringWithFormat:@"1.%i\n2.%i\n3.%i\n4.%i\n5.%i\n6.%i\n7.%i\n8.%i\n9.%i\n10.%i",easyRanking[0],easyRanking[1],easyRanking[2],easyRanking[3],easyRanking[4],easyRanking[5],easyRanking[6],easyRanking[7],easyRanking[8],easyRanking[9]];
	else if(rankingDifficulty==1)
		rankings.text=[NSString stringWithFormat:@"1.%i\n2.%i\n3.%i\n4.%i\n5.%i\n6.%i\n7.%i\n8.%i\n9.%i\n10.%i",mediumRanking[0],mediumRanking[1],mediumRanking[2],mediumRanking[3],mediumRanking[4],mediumRanking[5],mediumRanking[6],mediumRanking[7],mediumRanking[8],mediumRanking[9]];
	else if(rankingDifficulty==2)
		rankings.text=[NSString stringWithFormat:@"1.%i\n2.%i\n3.%i\n4.%i\n5.%i\n6.%i\n7.%i\n8.%i\n9.%i\n10.%i",hardRanking[0],hardRanking[1],hardRanking[2],hardRanking[3],hardRanking[4],hardRanking[5],hardRanking[6],hardRanking[7],hardRanking[8],hardRanking[9]];
}
/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	sound=TRUE;
	music=TRUE;
	difficulty=0;
	move1 =[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"move1" ofType:@"png"]];
	move2 =[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"move2" ofType:@"png"]];
	shoot1 =[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"shoot1" ofType:@"png"]];
	shoot2 =[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"shoot2" ofType:@"png"]];
	equation1 =[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"equation1" ofType:@"png"]];
	equation2 =[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"equation2" ofType:@"png"]];
	wrong1 =[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"wrong1" ofType:@"png"]];
	wrong2 =[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"wrong2" ofType:@"png"]];
	pause =[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"pause" ofType:@"png"]];
	tutorialImage.image=move1;
	tutPage=0;
	tutImage=FALSE;
	changeTutImage = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateImage) userInfo:nil repeats:YES];
    tutPrev.hidden=TRUE;
	tutorialDesc.text=@"MOVING\n Touch the screen and your ship will move towards just in front of the point that you touch. The ship will stop moving if you stop touching the screen. You will lose health if you crash into an asteroid.  \n \n 1/5 ";
	rankingDifficulty=0;
	[self loadRankings];
	rankings.text=[NSString stringWithFormat:@"1.%i\n2.%i\n3.%i\n4.%i\n5.%i\n6.%i\n7.%i\n8.%i\n9.%i\n10.%i",easyRanking[0],easyRanking[1],easyRanking[2],easyRanking[3],easyRanking[4],easyRanking[5],easyRanking[6],easyRanking[7],easyRanking[8],easyRanking[9]];
	[super viewDidLoad];
}
//loads the rankings
- (void)loadRankings{
	//later add loading rankings from file or online
	docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
	path = [docsDirectory stringByAppendingPathComponent:@"asteroidsRanking.txt"];
	fileContents = [NSString stringWithContentsOfFile:path];
	lines = [fileContents componentsSeparatedByString:@"."];
	int i=0;
	for(NSString *l in lines){
		NSLog(l);
		if(i<9)
			easyRanking[i]=[l intValue];
		else if(i<19)
			mediumRanking[i-10]=[l intValue];
		else if(i<29)
			hardRanking[i-20]=[l intValue];
		i++;
	}
}
//adds a score to the ranking
- (void)addRanking:(int)newScore:(int)rankDifficulty{
	//add online uploading/file saving later
	int position=-1;
	if(rankDifficulty==0){
		for(int i=9; i>=0;i--){
			if(easyRanking[i]<newScore)
				position=i;
		}
		if(position>=0){
			for(int j=9;j>position-1;j--){
				easyRanking[j]=easyRanking[j-1];
			}
			easyRanking[position]=newScore;
		}
	}else if(rankDifficulty==1){
		for(int i=9; i>=0;i--){
			if(mediumRanking[i]<newScore)
				position=i;
		}
		if(position>=0){
			for(int j=9;j>position-1;j--){
				mediumRanking[j]=mediumRanking[j-1];
			}
		mediumRanking[position]=newScore;
		}
	}else if(rankDifficulty==2){
		for(int i=9; i>=0;i--){
			if(hardRanking[i]<newScore)
				position=i;
		}
		if(position>=0){
			for(int j=9;j>position-1;j--){
				hardRanking[j]=hardRanking[j-1];
			}
			hardRanking[position]=newScore;
		}
	}
	if(rankingDifficulty==0)
		rankings.text=[NSString stringWithFormat:@"1.%i\n2.%i\n3.%i\n4.%i\n5.%i\n6.%i\n7.%i\n8.%i\n9.%i\n10.%i",easyRanking[0],easyRanking[1],easyRanking[2],easyRanking[3],easyRanking[4],easyRanking[5],easyRanking[6],easyRanking[7],easyRanking[8],easyRanking[9]];
	else if(rankingDifficulty==1)
		rankings.text=[NSString stringWithFormat:@"1.%i\n2.%i\n3.%i\n4.%i\n5.%i\n6.%i\n7.%i\n8.%i\n9.%i\n10.%i",mediumRanking[0],mediumRanking[1],mediumRanking[2],mediumRanking[3],mediumRanking[4],mediumRanking[5],mediumRanking[6],mediumRanking[7],mediumRanking[8],mediumRanking[9]];
	else if(rankingDifficulty==2)
		rankings.text=[NSString stringWithFormat:@"1.%i\n2.%i\n3.%i\n4.%i\n5.%i\n6.%i\n7.%i\n8.%i\n9.%i\n10.%i",hardRanking[0],hardRanking[1],hardRanking[2],hardRanking[3],hardRanking[4],hardRanking[5],hardRanking[6],hardRanking[7],hardRanking[8],hardRanking[9]];	
    save = [NSString stringWithFormat:@"%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.%i.",easyRanking[0],easyRanking[1],easyRanking[2],easyRanking[3],easyRanking[4],easyRanking[5],easyRanking[6],easyRanking[7],easyRanking[8],easyRanking[9],mediumRanking[0],mediumRanking[1],mediumRanking[2],mediumRanking[3],mediumRanking[4],mediumRanking[5],mediumRanking[6],mediumRanking[7],mediumRanking[8],mediumRanking[9],hardRanking[0],hardRanking[1],hardRanking[2],hardRanking[3],hardRanking[4],hardRanking[5],hardRanking[6],hardRanking[7],hardRanking[8],hardRanking[9]];
	dataToWrite = [save dataUsingEncoding:NSUTF8StringEncoding];
	docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
	path = [docsDirectory stringByAppendingPathComponent:@"asteroidsRanking.txt"];
	[dataToWrite writeToFile:path atomically:YES];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[glView dealloc];
	[label release];
	[resumeButton release];
	[lastView release];
	[gameCheck release];
	[options release];
	[changeTutImage release];
	[move1 release];
	[move2 release];
	[shoot1 release];
	[shoot2 release];
	[equation1 release];
	[equation2 release];
	[wrong1 release];
	[wrong2 release];
	[pause release];
	[tutNext release];
	[tutPrev release];
	[ranking release];
	[rankings release];
	[rankingSwitch release];
	[docsDirectory release];
	[path release];	
	[fileContents release];
	[lines release];
	[save release];
	[dataToWrite release];
    [super dealloc];
}


@end
